import {
  _decorator,
  Component,
  EventTouch,
  Input,
  input,
  Node,
  UITransform,
  Vec2,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("JoyStickManage")
export class JoyStickManage extends Component {
  input: Vec2 = Vec2.ZERO;
  private Body: Node;
  private Stick: Node;
  private DefaultPos: Vec2;
  private radius: number;
  onLoad() {
    this.Body = this.node.getChildByName("Body");
    this.Stick = this.Body.getChildByName("Stick");
    this.radius = this.Body.getComponent(UITransform).contentSize.x / 2;
    this.DefaultPos = new Vec2(this.Body.position.x, this.Body.position.y);
    input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
    input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
    input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
  }
  onDestroy() {
    input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
    input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
    input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
  }
  onTouchStart(e: EventTouch) {
    // console.log('TOUCH_START')
    // 获取点击屏幕的位置
    const touchPos = e.getUILocation();
    // 将摇杆设置在点击的位置
    this.Body.setPosition(touchPos.x, touchPos.y);
  }
  onTouchMove(e: EventTouch) {
    // console.log('TOUCH_MOVE')
    // 获取手指实时滑动的屏幕的位置
    const touchPos = e.getUILocation();
    const stickPos = new Vec2(
      touchPos.x - this.Body.position.x,
      touchPos.y - this.Body.position.y
    );
    // 限制stick的边界
    if (stickPos.length() > this.radius) {
      stickPos.multiplyScalar(this.radius / stickPos.length());
    }
    // 设置stick的位置
    this.Stick.setPosition(stickPos.x, stickPos.y);
    // 记录stick的位置
    this.input = stickPos.clone().normalize();
  }
  // 手指离开，复位
  onTouchEnd() {
    // console.log('TOUCH_END')
    this.Body.setPosition(this.DefaultPos.x, this.DefaultPos.y);
    this.Stick.setPosition(0, 0);
    this.input = Vec2.ZERO;
  }
}
